using System;
using System.Collections.Generic;
using System.Text;

namespace Developex.DatabaseWrapper
{
	/// <summary>
	/// 
	/// </summary>
	public class NestedTransactionWrapper
	{
		/// <summary>
		/// 
		/// </summary>
		public delegate void EmptyDelegate();

		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		public delegate T EmptyDelegate<T>();

		/// <summary>
		/// 
		/// </summary>
		/// <param name="conn"></param>
		/// <param name="del"></param>
		public static void WrapInTransaction(Connection conn, EmptyDelegate del)
		{
			if (conn.InTransaction)
				del();
			else
			{
				try
				{
					conn.BeginTransaction();

					del();

					conn.Commit();
				}
				finally
				{
					if (conn.InTransaction)
						conn.Rollback();
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="conn"></param>
		/// <param name="del"></param>
		public static T WrapInTransaction<T>(Connection conn, EmptyDelegate<T> del)
		{
			if (conn.InTransaction)
				return del();
			try
			{
				conn.BeginTransaction();

				T result = del();

				conn.Commit();

				return result;
			}
			finally
			{
				if (conn.InTransaction)
					conn.Rollback();
			}
		}
	}
}
